﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iNotesNotification
{
    public class 
        iNotesMailbox : IEnumerable<iNotesMessage>
    {
        protected List<iNotesMessage> _messages = new List<iNotesMessage>();
        protected Dictionary<string, iNotesMessage> _messageById = new Dictionary<string,iNotesMessage>();
        protected Dictionary<string, iNotesMessage> _newMessages = new Dictionary<string,iNotesMessage>();
        protected iNotesMessage _latestMessage = null;
        protected DateTime _lastSavePointDate = DateTime.MinValue;

        public iNotesMailbox() { }

        public iNotesMessage LatestEmail
        {
            get
            {
                return _latestMessage;
            }
        }

        public int MessageCount
        {
            get
            {
                return _messages.Count;
            }
        }

        public int NewMessageCount
        {
            get
            {
                return _newMessages.Count;
            }
        }

        public IEnumerable<iNotesMessage> NewMessages
        {
            get
            {
                return _newMessages.Values;
            }
        }

        public void Add(iNotesMessage message)
        {
            if (!_messageById.ContainsKey(message.UniqueID))
            {
                _messages.Add(message);
                _messageById[message.UniqueID] = message;

                if (message.Date > _lastSavePointDate)
                {
                    _newMessages[message.UniqueID] = message;
                }


                if (_latestMessage == null) _latestMessage = message;
                else if (_latestMessage.Date < message.Date) _latestMessage = message;
            }
        }

        public void MarkAsRead(iNotesMessage message)
        {
            if (_newMessages.ContainsKey(message.UniqueID))
            {
                _newMessages.Remove(message.UniqueID);

                if (_lastSavePointDate < message.Date) _lastSavePointDate = message.Date;
            }
        }

        public void Clear()
        {
            _messages.Clear();
            _messageById.Clear();
            _newMessages.Clear();
            _latestMessage = null;
            _lastSavePointDate = DateTime.MinValue;
        }

        public void Sort()
        {
            _messages.Sort();
        }

        public void MarkAsRead()
        {
            if (_latestMessage != null) 
                _lastSavePointDate = _latestMessage.Date;

            _newMessages.Clear();
        }

        public IEnumerator<iNotesMessage> GetEnumerator()
        {
            return _messages.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _messages.GetEnumerator();
        }
    }
}
